package academic.ui.server;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

import org.apache.torque.TorqueException;
import org.apache.torque.util.Criteria;

import ecommerce.soco.server.encrypt.Encrypt;
import ecommerce.soco.server.util.email.EmailUsers;

import ecommerce.soco.shared.GWT_Customer;
import torque.generated.City;
import torque.generated.Customers;
import torque.generated.CustomersCity;
import torque.generated.CustomersPeer;
import torque.generated.Emaillist;
import torque.generated.EmaillistPeer;

public class UserManager {

	public UserManager() {
		
	}
	
	private Customers customer;
	
	private Boolean isLoggedIn=false;
	
	public Boolean isLoggedIn() {
		return isLoggedIn;
	}
	
	public Boolean login(String userid,String passwd) {
		
		//TODO check the database for the userid/passwd combination if successful set isLoggedIn to true
		try {
			Criteria userCrit = new Criteria().add(CustomersPeer.EMAIL_ADDRESS,userid).add(CustomersPeer.PASSWORD,Encrypt.getHash(passwd));
			List<Customers> customer = CustomersPeer.doSelect(userCrit);
			if(customer!=null && customer.size()>0) {
				isLoggedIn=true;
				this.customer=customer.get(0);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TorqueException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		//TODO update the who's logged in table
		
		return isLoggedIn;
	}
	
	public void logout() {
		//TODO delete from the who's logged in table
		isLoggedIn = false;
	}
	
	public Integer register() {
		//TODO if the email address does not already exist in the system, insert the user and return the user id
		//If the user already exists throw an exception
		
		return -1;
	}

	public Customers getCurrentCustomer() {
		// TODO Auto-generated method stub
		return customer;
	}

	public int registerCustomer(GWT_Customer customerRegistration, City city) {
		Customers customer = new Customers();
		customer.setEmailAddress(customerRegistration.getEmailAddr());
		customer.setFirstname(customerRegistration.getFirstName());
		customer.setLastname(customerRegistration.getLastName());
		try {
			customer.setPassword(Encrypt.getHash(customerRegistration.getPassword()));
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		customer.setDateAdded(new Date());
		customer.setLastModified(new Date());
		customer.setNumLogins(1);
		try {
			customer.save();
			this.customer=customer;
			CustomersCity customersCity = new CustomersCity();
			customersCity.setCustomers(customer);
			customersCity.setCity(city);
			customersCity.save();
			isLoggedIn=true;
			return customer.getCustomersId();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}
	
	public static boolean customerExists(String emailAddr) {
		try {
			return CustomersPeer.doSelect(new Criteria().add(CustomersPeer.EMAIL_ADDRESS,emailAddr)).size()>0;
		} catch (TorqueException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public static String[] getFirstLastFromFull(String full) {
		String[] names = full.split(" ");
		int len = names.length;
		StringBuffer firstName = new StringBuffer();
        for (int i = 0; i < len - 1; i++)
        {
            if (firstName.length() == 0)
            {
                firstName.append(names[i]);
            } else
            {
                firstName.append(" ");
                firstName.append(names[i]);
            }
        }
        String[] returnNames=new String[2];
        returnNames[0]=firstName.toString();
        returnNames[1]=names[len-1];
        return returnNames;
	}
	
	public static Boolean updateEmailList(String email) {
		try {
			List<Emaillist> emails = EmaillistPeer.doSelect(new Criteria().add(EmaillistPeer.EMAIL, email.toUpperCase()).setIgnoreCase(true));
			if(emails==null || emails.size()<1)
			{//only update if the email is not currently in the master list
				Emaillist emailAddr = new Emaillist();
				emailAddr.setEmail(email);
				EmaillistPeer.doInsert(emailAddr);
				
				//any time this list is updated we should immediately send a welcome email
				EmailUsers.sendWelcomeEmail(email);
				
			}
			return true;
		} catch (TorqueException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
}
